import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_base/utils/log_utils.dart';
import '../../net/log_interceptor.dart' as MyLogInterceptor;

///
/// @DIR_PATH：lib/net
/// @TIME：2023/11/10 10:47
/// @AUTHOR：starr
/// dio网络请求封装
class DioUtils {
  static late final Dio _dio;

  //factory单例模式
  static final DioUtils _instance = DioUtils._internal();

  factory DioUtils() => _instance;

  //配置代理标识 false 标识不配置
  bool isProxy = false;

  //网络代理地址
  String proxyIp = "192.168.137.1";

  //网络代理端口
  String proxyPort = "8888";

  static Future<DioUtils> getInstance() async {
    return _instance;
  }

  DioUtils._internal() {
    BaseOptions options = BaseOptions();
    //请求超时时间
    // options.connectTimeout = 20000;
    // options.receiveTimeout = 2 * 60 * 1000;
    // options.sendTimeout = 2 * 60 * 1000;
    //初始化
    _dio = Dio(options);
    //当App运行在Release环境时，inProduction为true；
    // 当App运行在Debug和Profile环境时，inProduction为false。
    bool inProduction = const bool.fromEnvironment("dart.vm.product");
    if (!inProduction) {
      debugFunction();
    }
  }

  void debugFunction() {
    //添加log
    _dio.interceptors.add(MyLogInterceptor.LogInterceptor());
    //配置代理
    if (isProxy) {
      _setupProxy();
    }
  }

  //配置代理
  void _setupProxy() {
    // (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (HttpClient client) {
    //   client.findProxy = (uri) {
    //     //proxyIp 地址  proxyPort 端口
    //     return 'PROXY $proxyIp : $proxyPort';
    //   };
    //   client.badCertificateCallback =
    //       (X509Certificate cert, String host, int port) {
    //     //忽略证书
    //     return true;
    //   };
    //   return null;
    // };
  }

  /// get 请求
  ///[url]请求链接
  ///[queryParameters]请求参数
  ///[cancelTag] 取消网络请求的标识
  static Future<ResponseInfo> getRequest(
      {required String url,
      Map<String, dynamic>? queryParameters,
      CancelToken? cancelTag}) async {
    //发起get请求
    try {
      Response response = await _dio.get(url,
          queryParameters: queryParameters, cancelToken: cancelTag);
      //响应数据
      dynamic responseData = response.data;
      //数据解析
      if (responseData is Map<String, dynamic>) {
        //转换
        Map<String, dynamic> responseMap = responseData;
        int code = responseMap["errorCode"];
        if (code == 0) {
          //业务代码处理正常
          dynamic data = responseMap["data"];
          return ResponseInfo(data: data);
        } else {
          return ResponseInfo.error(errorMsg: "数据解析异常");
        }
      } else {
        //业务代码异常
        return ResponseInfo.error(errorCode: responseData["errorCode"]);
      }
    } catch (e, s) {
      //异常
      return errorController(e, s);
    }
  }

  ///
  ///
  ///
  static Future<ResponseInfo> postRequest(
      {required String url,
      required Map<String, dynamic> formDataMap,
      Map<String, dynamic>? jsonMap,
      CancelToken? cancelTag}) async {
    FormData form = FormData.fromMap(formDataMap);
    LogUtils.e("请求数据 $form");
    //发起post请求
    try {
      Response response =
          await _dio.post(url, data: form, cancelToken: cancelTag);
      LogUtils.e("响应数据 ${response.data}");
      //响应数据
      dynamic responseData = response.data;
      if (responseData is Map<String, dynamic>) {
        Map<String, dynamic> responseMap = responseData;
        int code = responseMap["errorCode"];
        if (code == 0) {
          //业务代码处理正常
          //获取数据
          dynamic data = responseMap["data"];
          return ResponseInfo(data: data);
        } else {
          //业务代码异常
          return ResponseInfo.error(
              errorCode: responseMap["errorCode"],
              errorMsg: responseMap["errorMsg"]);
        }
      } else {
        return ResponseInfo.error(errorMsg: "数据解析异常");
      }
    } catch (e, s) {
      return errorController(e, s);
    }
  }

  static Future<ResponseInfo> errorController(e, StackTrace s) {
    ResponseInfo responseInfo = ResponseInfo();
    //网络错误处理
    if (e is DioError) {
      DioError dioError = e;

    } else {
      //其他错误
      responseInfo.errorMsg = "未知错误";
    }
    return Future.value(responseInfo);
  }
}

class ResponseInfo {
  bool get success => errorCode == 0;
  late int errorCode;
  late String errorMsg;
  dynamic data;

  ResponseInfo({this.errorCode = 0, this.data, this.errorMsg = "请求成功"});

  ResponseInfo.error({
    this.errorCode = -1001,
    this.errorMsg = "登录失效，请重新登录",
  });
}
